import serve from 'koa-static';
import path from 'path';
import nunjucks from 'nunjucks';
import views from 'koa-views';
import mount from 'koa-mount';
import pagelet from './ext/pagelet';
import {dev,config} from "./config";
import utils from "./utils";
import compress from "koa-compress";
const compressOptions = { threshold: 2048 };

let publicDir = `/static`;


export var view_path = path.resolve(__dirname, `../dist/static/html`);

if (dev) {
    view_path = path.resolve(__dirname, `../static/html`);
} 

var nunjucks_env = nunjucks.configure(view_path, {
    autoescape: true,
    watch: true
});

// 配置 pagelet
pagelet.configure({
    root: view_path,
    manifest: path.join(view_path, 'manifest.json'),
    cache: true
});

// 注册 Tag 到 nunjucks
pagelet.register(nunjucks_env);
require("./filter").default(nunjucks_env);
require("./tag").default(nunjucks_env);
export default function(app) {
    
    app.use(compress(compressOptions));
    if(dev){
        app.use(mount('/static/image', serve(__dirname + '/' + '../static/image')));
    }
    
    app.use(serve(__dirname + '/' + '../dist' ));
    app.use(mount('/m3u8', serve(__dirname + '/' + '../../mp3')));
    
    app.use(views(view_path, {
        extension: 'html',
        cache: false,
        map: {
            html: 'nunjucks'
        }
    }));


    app.use(async(ctx, next) => {
        
        ctx.view = async function(html, data) {
            html = html + '.html';
            var view_context = ctx.__view || {};
            let session = ctx.userInfo ||await ctx.sess(),
                app_client = utils.getReferer(ctx);
            if(session){
                session.login = true;
            }else{
                session = {isLogin:false}
            }
            return await ctx.render(html, {
                ...view_context,
                ...data,
                publicDir,
                session,
                pageContext:{
                    mode:process.env.NODE_ENV,
                    app_client,
                    referer:ctx.header.referer ,
                },
            });

        };
        await next();
    });
}
